/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  MainZhiShiActivity.java   
 * @Package com.jiyi.activity.main   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-6-23 上午10:02:35   
 * @version V1.0     
 */
package com.jiyi.activity.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.bean.main.NewsListJson;
import com.jiyi.bean.main.NewsListJson.NewsBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.inteface.ClearEditTextInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.ClearEditText;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DeviceUtil;
import com.swift.utils.GlideUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ClassName: MainZhiShiActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-6-23 上午10:02:35
 * 
 */
public class MainZhiShiFragment extends Fragment {

	@BindView(R.id.etSearch)
	ClearEditText etSearch;
	@BindView(R.id.llZhiShi)
	LinearLayout llZhiShi;
	@BindView(R.id.llContent)
	LinearLayout llContent;
	@BindView(R.id.rlTip)
	RelativeLayout rlTip;

	List<NewsBean> newsList = new ArrayList<NewsBean>();

	LayoutInflater inflater;

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_main_zhishi, null, false);
		ButterKnife.bind(this, view);
		this.inflater = inflater;
		init();
//		EventBus.getDefault().register(this);
		return view;
	}

//	@Subscribe
//	public void onZhiShiListEvent(ZhiShiListEvent zhiShiListEvent) {
//		switch (zhiShiListEvent.type) {
//		case ZhiShiListEvent.MAIN_ZHISHI_FRAGMENT:
//			search();
//			break;
//
//		default:
//			break;
//		}
//	}

	@Override
	public void onDestroy() {
//		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	private void init() {
		initViewState();
		getData(null);
	}
	
	private void initViewState() {
		// 设置输入法的搜索事件
		etSearch.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH
						|| actionId == EditorInfo.IME_ACTION_DONE) {
					InputMethodManager imm = (InputMethodManager) v
							.getContext().getSystemService(
									Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

					Log.e("onEditorAction  ", "   done ");
					search();
					return true;
				}
				return false;
			}
		});
		etSearch.setClearEditTextInterface(new ClearEditTextInterface() {

			@Override
			public void onClear() {
				getData(null);
			}
		});
	}

	/**
	 * @author: HYM
	 * @Title: getData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-7-21
	 */
	private void getData(String keyWord) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		if (!TextUtils.isEmpty(keyWord)) {
			params.put("keyWord", keyWord);
		}

		VolleyRequest.StringRequestPost(getContext(), WebApi.MAIN_ZHISHI_LIST,
				"", params, new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								NewsListJson temp = new Gson().fromJson(result,
										NewsListJson.class);
								if (temp != null) {
									if (temp.getData().getArtList().size() <= 0) {
										rlTip.setVisibility(View.VISIBLE);
										llContent.setVisibility(View.GONE);
									} else {
										rlTip.setVisibility(View.GONE);
										llContent.setVisibility(View.VISIBLE);
										newsList.clear();
										newsList.addAll(temp.getData().getArtList());
										fillNewZhiShi();
									}
									
								}
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}


	void search() {
		getData(etSearch.getText().toString());
	}
	
	private void fillNewZhiShi() {
		llZhiShi.removeAllViews();
		for (int i = 0; i < newsList.size(); i++) {
			final NewsBean obj = newsList.get(i);
			 View view = inflater.inflate(R.layout.item_main_zhishi, null, false);
			view.setTag(i);
			final LinearLayout root = (LinearLayout) view.findViewById(R.id.root);
			root.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					TextView tvZhiShiReadNum = (TextView) root
							.findViewById(R.id.tvZhiShiReadNum);
					tvZhiShiReadNum.setText((Integer.parseInt(tvZhiShiReadNum.getText().toString())+1)+"");
					Intent intent = new Intent(v.getContext(),
							ZhiShiDetailActivity.class);
					intent.putExtra("type", "zhishi");
					intent.putExtra("id", obj.getId());
					v.getContext().startActivity(intent);
				}
			});
			TextView tvZhiShiTitle = (TextView) view
					.findViewById(R.id.tvZhiShiTitle);
			tvZhiShiTitle.setText(obj.getTitle());
			TextView tvZhiShiContent = (TextView) view
					.findViewById(R.id.tvZhiShiContent);
			tvZhiShiContent.setText(obj.getContent());
			
			ImageView ivCover = (ImageView) view.findViewById(R.id.ivCover);
			GlideUtil.load(getContext(), obj.getImage(), ivCover);
			TextView tvZhiShiReadNum = (TextView) view
					.findViewById(R.id.tvZhiShiReadNum);
			tvZhiShiReadNum.setText(obj.getReading()+"");
			llZhiShi.addView(view);
			View spi = new View(getActivity());
			spi.setBackgroundColor(getResources().getColor(
					R.color.base_bg_color));
			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
					(int) (10 * DeviceUtil.getInstance().getBiLi()));
			spi.setLayoutParams(params);
			llZhiShi.addView(spi);
		}
	}
}
